<?php
/*
 * Nebulae
 * Operações de file system
 */

// Função recursiva para copiar todos os conteudos de um directorio
function r_copy_dir( $source, $target ) {
	if ( is_dir( $source ) )
	{
		@mkdir( $target );
		$d = dir( $source );
           
		while ( FALSE !== ( $entry = $d->read() ) ) 
		{
			if ( $entry == '.' || $entry == '..' )
			{
				continue;
			}
               
			$Entry = $source . '/' . $entry;           
			if ( is_dir( $Entry ) )
			{
				full_copy( $Entry, $target . '/' . $entry );
				continue;
			}
			copy( $Entry, $target . '/' . $entry );
		}
           
		$d->close();
	} else {
		copy( $source, $target );
	}
}

// A function to copy files from one directory to another one, including subdirectories and
// nonexisting or newer files. Function returns number of files copied.
// This function is PHP implementation of Windows xcopy  A:\dir1\* B:\dir2 /D /E /F /H /R /Y
// Syntaxis: [$number =] dircopy($sourcedirectory, $destinationdirectory [, $verbose]);
// Example: $num = dircopy('A:\dir1', 'B:\dir2', 1);

function dircopy($srcdir, $dstdir, $verbose = false) {
	echo $srcdir . "-->" . $dstdir;
  $num = 0;
  //if(!is_dir($dstdir)) mkdir($dstdir);
  if(!is_dir($dstdir)) {
	mkdir($dstdir);
  } else {
	echo "erro a criar o directorio de destino";
  }
  if($curdir = opendir($srcdir)) {
    while($file = readdir($curdir)) {
      if($file != '.' && $file != '..') {
        $srcfile = $srcdir . '/' . $file;
        $dstfile = $dstdir . '/' . $file;
        if(is_file($srcfile)) {
          if(is_file($dstfile)) $ow = filemtime($srcfile) - filemtime($dstfile); else $ow = 1;
          if($ow > 0) {
            if($verbose) echo "Copying '$srcfile' to '$dstfile'...";
            if(copy($srcfile, $dstfile)) {
              touch($dstfile, filemtime($srcfile)); $num++;
              if($verbose) echo "OK\n";
            }
            else echo "Error: File '$srcfile' could not be copied!\n";
          }                  
        }
        else if(is_dir($srcfile)) {
          $num += dircopy($srcfile, $dstfile, $verbose);
        }
      }
    }
    closedir($curdir);
  } else {
	echo "nao foi possivel abrir o directorio para leitura $srcdir";
  }
  return $num;
}


/******  Função adaptadada do código de exemplo submetida em php.com *****\
* Funcao elimina o dir e todos os subdirs
* Autor ggarciaa@gmail.com (04-July-2007 01:57)
* Parametros:
* $dir ---> Caminho para o directorio a eliminar
* $eDir ---> Elimininar o directorio 1/0
\******************************************************************/
function eliminarDirectorio($dir, $DeleteMe) 
{
	if(!$dh = @opendir($dir)) return;
    while (false !== ($obj = readdir($dh))) {
        if($obj=='.' || $obj=='..') continue;
        if (!@unlink($dir.'/'.$obj)) eliminarDirectorio($dir.'/'.$obj, true);
    }
    if ($DeleteMe){
        closedir($dh);
        @rmdir($dir);
    }
}
?>